//
//  ZXComposeController.m
//  ZXOCWeiBo
//
//  Created by mac on 15/12/6.
//  Copyright © 2015年 itcast. All rights reserved.
//

#import "ZXComposeController.h"
#import "ZXTextView.h"
#import "ZXStatuses.h"
#import "ZXComposeToolBar.h"
#import "ZXComposePhotosView.h"
#import "ZXStatusBar.h"
#import "ZXStatusTool.h"
#import "ZXSendStatusParam.h"
#import "ZXSendStatuResult.h"

@interface ZXComposeController ()<UITextViewDelegate,ZXComposeToolBarDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,weak)ZXTextView * textView;


@property(nonatomic,weak)ZXComposeToolBar* toolBar;

@property(nonatomic,weak) UIImagePickerController * imagePicker;
//判断键盘是否弹出
@property(nonatomic,assign,getter=isKbShowing)BOOL kbShowing;
/**
 *  创建一个ZXComposePhotosView来引着它要不然在选择照片的时候就会被销毁
 */
@property(nonatomic,weak)ZXComposePhotosView * photosView;

/**
 *  返回结果的判断
 */
@property(nonatomic,strong)ZXStatuses* statusResult;

@end

@implementation ZXComposeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //添加导航栏的按钮
    [self setaddnavItem];
    
    //添加textView
    [self setaddTextView];
    
   //添加工具条
    [self setaddToolBtn];
    
    //监听键盘的事件
    [self keyboarNotification];
    
//    一进来就弹出键盘
    [self.textView becomeFirstResponder];
}
#define mark 键盘通知
//监听键盘
-(void)keyboarNotification
{
//    键盘将要弹出的时候
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ktWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ktWillhide:) name:UIKeyboardWillHideNotification object:nil];
}
//监听键盘将要弹出的方法
-(void)ktWillShow:(NSNotification *)notifi
{
//    ZXLog(@"%@",notifi.userInfo);
//
//    //键盘弹出的时间
    double duration = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    //获得键盘的高度
    CGRect rect = [notifi.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kbHeihgt = rect.size.height;
    
[UIView animateWithDuration:duration animations:^{
     self.toolBar.transform = CGAffineTransformMakeTranslation(0, -kbHeihgt);
}];
   
//    self.toolBar.y = 370;
}
//监听键盘将要隐藏的时候
-(void)ktWillhide:(NSNotification *)notifi
{
    
    //键盘弹出的时间
    double duration = [notifi.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
//        恢复原位
        self.toolBar.transform = CGAffineTransformIdentity;
    }];

    //    self.toolBar.y = self.view.h - 40;
}
#define maek ---初始化控件添加按钮
/**
 *  添加导航栏的按钮
 */
-(void)setaddnavItem
{
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barBtnItemWithTitl:@"取消" target:self action:@selector(cancel)];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barBtnItemWithTitl:@"发送" target:self action:@selector(send)];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem.enabled = NO;
}
/**
 *  添加textView
 */
-(void)setaddTextView
{
    //添加UITexVIew
    ZXTextView * text = [[ZXTextView alloc]init];
    text.frame = self.view.bounds;
    text.font = [UIFont systemFontOfSize:16];
    text.placeHolder = @"分享新鲜事物。。。";
#warning 因为UITextView是继承UIScrollView的所有可以滚动
//    设置滚动
    text.alwaysBounceVertical =YES;
    
#warning UITextView没有placeHolder 我们要自定义一个UITextView
    [self.view addSubview:text];
    self.textView = text;
    text.delegate = self;
    
    ZXComposePhotosView * photosView = [[ZXComposePhotosView alloc]initWithFrame:CGRectMake(0, 80, self.view.w, 300)];
    photosView.backgroundColor = [UIColor yellowColor];
    self.photosView = photosView;
    
    [self.textView addSubview:photosView];
}
/**
 *  添加工具条
 */
-(void)setaddToolBtn
{
    //添加工具条
    ZXComposeToolBar * toolbar = [[ZXComposeToolBar alloc]init];
    toolbar.delegate =self;
    
    CGFloat toolbarW = self.view.w;
    CGFloat toolbarH = 40;
    CGFloat toolbarX = 0;
    CGFloat toolbarY = self.view.h - toolbarH;
    
    toolbar.frame = CGRectMake(toolbarX, toolbarY, toolbarW, toolbarH);
    [self.view addSubview:toolbar];
    self.toolBar = toolbar;
}


/**
 *  当text的内容发生改变的时候会调用这个方法
 */
-(void)textViewDidChange:(UITextView *)textView
{
    ZXLog(@"");
    self.navigationItem.rightBarButtonItem.enabled = textView.text.length > 0;
    
}

//监听取消按钮
-(void)cancel
{
    ZXLog(@"点击了");
    //取消当前控制器
    [self dismissViewControllerAnimated:YES completion:nil];
}
//监听发送按钮
-(void)send
{
    [ZXStatusBar showTip:@"正在发送。。。。"];
    
    if (self.photosView.harImgs)
    {
        //发送带有图片的
        [self shengWeiboWithImgs];
    }
    else
    {
        //发送纯文字
        [self shengWeiboWithoutImgs];
    }
    
    
}
//带图片的微博
-(void)shengWeiboWithImgs
{
    NSString * url = @"https://upload.api.weibo.com/2/statuses/upload.json";
    
    AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    params[@"access_token"] = [ZXAccount shareAccount].access_token;
    params[@"status"] = self.textView.text;
    
    [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //获取图片数据（获取第一张）
        UIImage *img1 = self.photosView.images[0];
        //什么格式的图片 ， 图片上传压缩比例0.7
        NSData * img1Data = UIImageJPEGRepresentation(img1, 0.7);
        
//        上传那张图片appendPartWithFileData 上传图片的所需要的字段名name 图片的名字fileName 图片的格式mimeType
        [formData appendPartWithFileData:img1Data name:@"pic" fileName:@"aaa.jog" mimeType:@"image/jpeg"];
#warning 新浪内部设置了其他的应用只能上传一张图片
//        //获取图片数据（获取第2张）
//        UIImage *img2 = self.photosView.images[1];
//        //什么格式的图片 ， 图片上传压缩比例0.7
//        NSData * img2Data = UIImageJPEGRepresentation(img2, 0.7);
//        
//        //        上传那张图片appendPartWithFileData 上传图片的所需要的字段名name 图片的名字fileName 图片的格式mimeType
//        [formData appendPartWithFileData:img2Data name:@"pic" fileName:@"aabbba.jog" mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        //判断这个返回一定是json字典的数据
        if ([responseObject isKindOfClass:[NSDictionary class]])
        {
            self.statusResult = [ZXStatuses objectWithKeyValues:responseObject];
        }
        //判断处理结果
        [self handlerResult];
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
         ZXLog(@"%@",error);
        if (error)
        {
            [self showTipAffter:@"发送失败。。。"];
            
        }
    }] ;
}

//发送纯文字的微博
-(void)shengWeiboWithoutImgs
{
    NSString * url = @"https://api.weibo.com/2/statuses/update.json";
    
//    NSMutableDictionary * param = [NSMutableDictionary dictionary];
//    param[@"access_token"]=[ZXAccount shareAccount].access_token;
//    param[@"status"] = self.textView.text;
    
    ZXSendStatusParam * param = [ZXSendStatusParam param];
    param.status = self.textView.text;
    
    [ZXStatusTool sendStatusWithUrl:url params:param success:^(ZXSendStatuResult *result) {
        //给结果赋值
        self.statusResult = result;
//        处理结果
        [self handlerResult];
    } failure:^(NSError *error) {
        [self showTipAffter:@"发送失败"];
    }];

}
#define mark scrollView的代理方法
//当滚动的时候会调用
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    ZXLog(@"滚动了");
    //隐藏键盘
    [self.view endEditing:YES];
}
//在控制器将要销毁的时候
-(void)viewWillDisappear:(BOOL)animated
{
    //隐藏键盘
    [self.view endEditing:YES];
}
//控制器销毁的时候调用
-(void)dealloc
{
    ZXLog(@"移除了通知");
//    移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#define mark ZXComposeToolBarDelegate的代理方法
-(void)composeToolBar:(ZXComposeToolBar *)toolbar btnType:(ToolBarBtnType)btnType
{
    //设置键盘显示标识
    //判断两个的偏移值是否相同
 BOOL isIdentity = CGAffineTransformEqualToTransform(self.toolBar.transform, CGAffineTransformIdentity);
    self.kbShowing = !isIdentity;
    
    switch (btnType) {
        case ToolBarBtnTypePicture:
            ZXLog(@"选择了图片");
            [self showImagePickController];
            break;
            
        default:
            break;
    }
}
#pragma mark 弹出图片选择器
-(void)showImagePickController
{
    //创建一个图片选择控制器
    UIImagePickerController * imagePickercontr = [[UIImagePickerController alloc]init];
    
    //设置它的类型
    imagePickercontr.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    //设置代理方法
    imagePickercontr.delegate = self;
    
    //摩达出一个控制器
    [self presentViewController:imagePickercontr animated:YES completion:nil];
}
#pragma mark  UIImagePickerController的代理方法
//选择那张图片
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
  
    UIImage * image = info[UIImagePickerControllerOriginalImage];
    [self.photosView addImag:image];
    //销毁图片选择器
    [self dismissViewControllerAnimated:YES completion:nil];
    
    //让textView 成为第一响应者
    if (self.isKbShowing)
    {
        [self.textView becomeFirstResponder];
    }
    
}
/**
 *  处理返回的结果
 */
-(void)handlerResult
{
    if (self.statusResult.idstr)
    {
        //销毁当前控制器
        [self dismissViewControllerAnimated:YES completion:^{
            [self showTipAffter:@"发送成功。。。"];
        }];
    }
    else
    {
        [self dismissViewControllerAnimated:YES completion:^{
            [self showTipAffter:@"发送失败。。。"];
        }];
    }
}
/**
 *  延时显示tip
 */
-(void)showTipAffter:(NSString *)tip
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [ZXStatusBar showTip:tip];
    });
}

@end
